package ${packageName}.service;

import ${packageName}.entity.${className};
import ${packageName}.mapper.${className}Mapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
<#if enableRedis>
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
</#if>
import lombok.extern.slf4j.Slf4j;
<#if hasDateType>
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
</#if>
<#if hasBigDecimal>
import java.math.BigDecimal;
</#if>

import java.util.List;

/**
 * ${tableComment!''} Service
 * 
 * @author ${author}
 * @date ${.now?string("yyyy-MM-dd HH:mm:ss")}
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
<#if enableRedis>
@CacheConfig(cacheNames = "${cacheName}")
</#if>
public class ${className}Service extends ServiceImpl<${className}Mapper, ${className}> {

    @Autowired
    private ${className}Mapper ${lowerClassName}Mapper;
    


    /**
     * 创建${tableComment!'记录'}
     */
<#if enableRedis>
    @CacheEvict(allEntries = true)
</#if>
    public ${className} create(${className} ${lowerClassName}) {
        log.info("Create ${tableComment!'record'}: {}", ${lowerClassName});
        
        // 保存到数据库
        ${lowerClassName}Mapper.insert(${lowerClassName});
        
        return ${lowerClassName};
    }

    /**
     * 根据ID查询
     */
<#if enableRedis>
    @Cacheable(key = "#id")
</#if>
    public ${className} findById(${primaryKeyType} id) {
        log.info("Query by ID: {}", id);
        return ${lowerClassName}Mapper.selectById(id);
    }

<#if hasCompositePrimaryKey!false>
    /**
     * 根据复合主键查询
     */
    public ${className} findByCompositeKey(${className} queryParam) {
        log.info("Query by composite key: {}", queryParam);
        QueryWrapper<${className}> queryWrapper = new QueryWrapper<>();
        
        // 构建复合主键查询条件
<#list columns as column>
    <#if column.primaryKey>
        if (queryParam.get${column.javaPropertyName}() != null) {
            queryWrapper.eq("${column.columnName}", queryParam.get${column.javaPropertyName}());
        }
    </#if>
</#list>
        
        return ${lowerClassName}Mapper.selectOne(queryWrapper);
    }
</#if>

    /**
     * 查询所有记录
     */
    public List<${className}> findAll() {
        log.info("Query all records");
        return ${lowerClassName}Mapper.selectList(null);
    }

    /**
     * 分页查询
     */
    public Page<${className}> findAll(int current, int size) {
        log.info("Paginated query: current={}, size={}", current, size);
        Page<${className}> page = new Page<>(current, size);
        return ${lowerClassName}Mapper.selectPage(page, null);
    }

    /**
     * 更新记录
     */
<#if enableRedis>
    @CacheEvict(allEntries = true)
</#if>
    public ${className} update(${className} ${lowerClassName}) {
        log.info("Update record: {}", ${lowerClassName});
        
<#if hasSinglePrimaryKey!false>
        if (${lowerClassName}Mapper.selectById(${lowerClassName}.get${primaryKeyProperty}()) == null) {
            throw new RuntimeException("Record not found");
        }
        
        // 更新到数据库
        ${lowerClassName}Mapper.updateById(${lowerClassName});
<#else>
        // 对于复合主键表，直接更新（MyBatis-Plus会根据所有主键字段进行更新）
        ${lowerClassName}Mapper.updateById(${lowerClassName});
</#if>
        
        return ${lowerClassName};
    }

    /**
     * 根据ID删除
     */
<#if enableRedis>
    @CacheEvict(key = "#id")
</#if>
    public void deleteById(${primaryKeyType} id) {
        log.info("Delete record: {}", id);
        
        if (${lowerClassName}Mapper.selectById(id) == null) {
            throw new RuntimeException("Record not found");
        }
        
        ${lowerClassName}Mapper.deleteById(id);
    }

<#if hasCompositePrimaryKey!false>
    /**
     * 根据复合主键删除
     */
    public void deleteByCompositeKey(${className} deleteParam) {
        log.info("Delete by composite key: {}", deleteParam);
        
        QueryWrapper<${className}> queryWrapper = new QueryWrapper<>();
        
        // 构建复合主键查询条件
<#list columns as column>
    <#if column.primaryKey>
        if (deleteParam.get${column.javaPropertyName}() != null) {
            queryWrapper.eq("${column.columnName}", deleteParam.get${column.javaPropertyName}());
        }
    </#if>
</#list>
        
        if (${lowerClassName}Mapper.selectOne(queryWrapper) == null) {
            throw new RuntimeException("Record not found");
        }
        
        ${lowerClassName}Mapper.delete(queryWrapper);
    }
</#if>

    /**
     * 批量删除
     */
<#if enableRedis>
    @CacheEvict(allEntries = true)
</#if>
    public void deleteAll(List<${primaryKeyType}> ids) {
        log.info("Batch delete: {}", ids);
        ${lowerClassName}Mapper.deleteBatchIds(ids);
    }

    /**
     * 检查记录是否存在
     */
    public boolean existsById(${primaryKeyType} id) {
        return ${lowerClassName}Mapper.selectById(id) != null;
    }

    /**
     * 统计总记录数
     */
    public long count() {
        return ${lowerClassName}Mapper.selectCount(null);
    }

<#list columns as column>
    <#if !column.primaryKey>
    /**
     * 根据${column.columnComment!''}查询
     */
    public List<${className}> findBy${column.javaPropertyName}(${column.javaType} ${column.javaFieldName}) {
        log.info("Query by ${column.columnComment!''}: {}", ${column.javaFieldName});
        QueryWrapper<${className}> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("${column.columnName}", ${column.javaFieldName});
        return ${lowerClassName}Mapper.selectList(queryWrapper);
    }
    
    </#if>
</#list>
}
